package com.imooc.order.controller;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.imooc.order.VO.ResultVO;
import com.imooc.order.converter.OrderForm2OrderDTO;
import com.imooc.order.dto.OrderDTO;
import com.imooc.order.enums.ResultEnum;
import com.imooc.order.exception.OrderException;
import com.imooc.order.form.OrderForm;
import com.imooc.order.service.OrderService;
import com.imooc.order.utils.ResultVOUtil;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	
	@PostMapping("/create")
	public ResultVO<Map<String,String>> create(@Valid OrderForm orderForm,BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			log.error("参数不正确,orderform={}",orderForm);
			throw new OrderException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
		}
		
		OrderDTO dto = OrderForm2OrderDTO.convert(orderForm);
		if(CollectionUtils.isEmpty(dto.getOrderDetailList())) {
			log.error("购物车为空");
			throw  new OrderException(ResultEnum.CART_ENPTY);
		}
		
		OrderDTO result = orderService.create(dto);
		
		Map<String ,String> map = new HashMap<>();
		map.put("orderId", result.getOrderId());
		
		return ResultVOUtil.success(map);
	}
}
